/*
 * Developer : Jack Matthews
 * Email: developer@droidprofessor.com
 * 
 * Copyright (C) 2010 http://droidprofessor.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.droidprofessor.android.library.phonelicenses;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.droidprofessor.android.library.phonelicenses.R;
import com.droidprofessor.android.library.phonelicenses.ApplicationDataCache.PaymentMethod;
import com.droidprofessor.android.licensegenerator.client.AndroidClientLicenseImpl;
import com.droidprofessor.android.licensegenerator.client.LicenseType;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class ActivityMain extends Activity implements OnClickListener,HttpResponseListener {
	private static final String TAG = "ActivityMain";

	//Views
	private Button btnSubmit, btnLoginRegister;
	private TextView textViewApplicationName, textViewDescription;
	private ProgressBar progressBarDownloadProgress;
	private Spinner spinnerPaymentMethod;
	private LinearLayout linearLayoutPaymentControls, linearLayoutContentHolder;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.com_phonelicenses_main);
		getControls();
		
		if(Environment.DEBUG) Toast.makeText(this, "DEBUG MODE", Toast.LENGTH_LONG).show();
		
	}



	


	/**
	 * Get hold of the XML Views
	 */
	private void getControls() {
		btnSubmit = (Button) findViewById(R.id.submit);
		btnLoginRegister = (Button) findViewById(R.id.loginregister);
		spinnerPaymentMethod = (Spinner) findViewById(R.id.paymentMethod);
		progressBarDownloadProgress=(ProgressBar)findViewById(R.id.downloadProgress);
		textViewApplicationName = (TextView)findViewById(R.id.heading);
		textViewDescription = (TextView)findViewById(R.id.content);
		linearLayoutPaymentControls = (LinearLayout)findViewById(R.id.paymentControls);
		linearLayoutContentHolder = (LinearLayout)findViewById(R.id.contentHolder);
		
		btnSubmit.setOnClickListener(this);
		btnLoginRegister.setOnClickListener(this);
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		
		switch (resultCode) {
			//Attempt to download the license
			case PhoneLicensesCodes.RESULT_CODE_LOGGED_IN:
				//The user may already have paid so attempt to download the license
				AndroidClientLicenseImpl.getInstance().downloadAndInstallLicense(this);
				break;
		}

	}


	@Override
	protected void onResume() {
		super.onResume();
		
		//Check the current state we are in
		determineViewState();
	}



	/**
	 * Determine the operation to do on load
	 * 
	 */
	private void determineViewState() {
		//by default we will no show any payment methods until
		//all the application information is downloaded
		hideAllPaymentControls();
		
		boolean verifiedAccount = PreferencesHelper.isAccountVerified(this);
		boolean verifiedPayment = PreferencesHelper.isPaymentVerified(this);
		boolean licenseInstalled = AndroidClientLicenseImpl.getInstance().isLicenseInstalled(this);
		
		if (licenseInstalled ) //we have a valid license
			stateLicenseInstalled();
		else if( !Utils.gotInternetConnection(this) ) //we don't have any internet connection
			stateNoInternet();
		else if( verifiedPayment ) //we are awaiting payment approval
			statePaymentPending();
		else { //no license installed
			stateNoLicense();
			
			//if we are not logged in yet, disable the appropriate controls
			if(!verifiedAccount) {
				this.spinnerPaymentMethod.setEnabled(false);
				this.btnSubmit.setEnabled(false);
				this.btnLoginRegister.setEnabled(true);
			} else {
				this.btnLoginRegister.setEnabled(false);
				this.spinnerPaymentMethod.setEnabled(true);
				this.btnSubmit.setEnabled(true);
			}
			
			//Check if we have not already downloaded the application information
			if(ApplicationDataCache.getInstance().isPopulated() ) {
				doActivityStateBasedOnLicenseType();
			} else {
				checkDeprecatedApp();
			}
			
		}
	}
	
	
	/**
	 * Hides the payment controls
	 */
	private void hideAllPaymentControls() {
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
	}



	/**
	 * Get the price information from the server
	 */
	private void downloadApplicationInformation() {
		
		//Check for an internet connection
		if( !Utils.gotInternetConnection(this) ) {
			stateNoInternet();
			return;
		}
		
		//show the progress bar
		this.progressBarDownloadProgress.setVisibility(View.VISIBLE);

		//Joomla requirements
		List<NameValuePair> get = new ArrayList<NameValuePair>();
		get.add(new BasicNameValuePair("option", "com_phonelicenses" ));    
		get.add(new BasicNameValuePair("view", "appinfo" ));    
		get.add(new BasicNameValuePair("controller", "appinfo" ));    
		get.add(new BasicNameValuePair("task", "getinfo" ));    
		get.add(new BasicNameValuePair("format", "xml" )); 	
		get.add(new BasicNameValuePair("application_id", AndroidClientLicenseImpl.getInstance().getApplicationId() )); 
		get.add(new BasicNameValuePair("auth_key", AndroidClientLicenseImpl.getInstance().getAuthKey() ));

		HttpUrlRequest.sendRequest(
				AndroidClientLicenseImpl.getInstance().getScheme(),
				AndroidClientLicenseImpl.getInstance().getHost(),
				AndroidClientLicenseImpl.getInstance().getPort(), 
				AndroidClientLicenseImpl.getInstance().getPath(),
				get, 
				null, 
				PhoneLicensesCodes.REQUEST_CODE_APPINFO,
				this
		);
	}
	
	
	
	
	/**
	 * Get the price information from the server
	 */
	private void checkDeprecatedApp() {
		
		//Check for an internet connection
		if( !Utils.gotInternetConnection(this) ) {
			stateNoInternet();
			return;
		}

		
		//show the progress bar
		this.progressBarDownloadProgress.setVisibility(View.VISIBLE);

		//Joomla requirements
		List<NameValuePair> get = new ArrayList<NameValuePair>();
		get.add(new BasicNameValuePair("option", "com_phonelicenses" ));        
		get.add(new BasicNameValuePair("task", "checkDeprecatedApp" ));    
		get.add(new BasicNameValuePair("format", "raw" )); 	
		get.add(new BasicNameValuePair("applicationId", AndroidClientLicenseImpl.getInstance().getApplicationId() )); 

		HttpUrlRequest.sendRequest(
				AndroidClientLicenseImpl.getInstance().getScheme(),
				AndroidClientLicenseImpl.getInstance().getHost(),
				AndroidClientLicenseImpl.getInstance().getPort(), 
				AndroidClientLicenseImpl.getInstance().getPath(),
				get, 
				null, 
				PhoneLicensesCodes.REQUEST_CODE_DEPRECATED,
				this
		);
	}
	
	
	
	
	private void showMessageDialog(String message) {
		dialogMessage = message;
		showDialog(PhoneLicensesCodes.DIALOG_MESSAGE);
	}
	
	private void showMessageDialog(int message) {
		dialogMessage = getString(message);
		showDialog(PhoneLicensesCodes.DIALOG_MESSAGE);
	}	
	
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_MESSAGE:
			dialog = new AlertDialog.Builder(this)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setMessage(dialogMessage)
			.setPositiveButton(R.string.com_phonelicenses_ok, null)
			.create();
			break;
		case PhoneLicensesCodes.DIALOG_LOGIN_REGISTER:
			dialog = new AlertDialog.Builder(this)
			.setTitle( ApplicationDataCache.getInstance().getMerchantName() )
			.setItems(R.array.loginRegister, new DialogInterface.OnClickListener() {
				Intent intent;
				@Override
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case 0:
						intent = new Intent(ActivityMain.this, ActivityLogin.class);
						intent.setAction(Intent.ACTION_VIEW);
						startActivityForResult(intent, PhoneLicensesCodes.REQUEST_CODE_LOGIN);	
						break;
					case 1:
						intent = new Intent(ActivityMain.this, ActivityRegister.class);
						intent.setAction(Intent.ACTION_VIEW);
						startActivity(intent);	
						break;
					}
				}
			})
			.create();
			break;
		default:
			dialog = null;
			break;
		}
		
		return dialog;
	}
	
	




	private String dialogMessage = "";
	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		super.onPrepareDialog(id, dialog);
		
		switch (id) {
		case PhoneLicensesCodes.DIALOG_MESSAGE:
			((AlertDialog)dialog).setMessage(dialogMessage);
			break;
		default:
			break;
		}
	}
	
	



	@Override
	public void onClick(View v) {
		Intent intent;

		switch (v.getId()) {
			case R.id.submit:
				//in case there are no payment methods
				if(spinnerPaymentMethod.getCount() < 1) {
					showMessageDialog("There are no payment methods available");
				} else {
					intent = new Intent(this, ActivityPayment.class);
					intent.setAction(Intent.ACTION_VIEW);
					
					//Pass the reference name to the Activity
					intent.putExtra("refName", selectedPaymentMethod.getRefName());
					startActivity(intent);
					finish(); //close the current activity	
				}

				break;
			case R.id.loginregister: 
				showDialog(PhoneLicensesCodes.DIALOG_LOGIN_REGISTER);
				break;
		}
	}



	/**
	 * Open the users email client to ask a question about the application
	 * 
	 * XML response must have been downloaded before calling this method
	 */
	private void askQuestion() {
		String subject = "";
		
		String body = getString(R.string.com_phonelicenses_enter_your_question_here);
		
		try {
			PackageInfo pinfo = getPackageManager().getPackageInfo(this.getPackageName(), 0);
			subject = "Question: "+ApplicationDataCache.getInstance().getApplicationName()+" "+pinfo.versionName;
		} catch (NameNotFoundException e) {
			Log.e(TAG, "NameNotFoundException" , e);
		}
		
		
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.setType("text/html");
		emailIntent .putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ApplicationDataCache.getInstance().getSupportEmail()});
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml(body));
		startActivity(Intent.createChooser(emailIntent, "Email:"));
	}



	@Override
	public void onResponseReceived(HttpResponse response, int requestCode) {
		switch (requestCode) {
		case PhoneLicensesCodes.REQUEST_CODE_DEPRECATED:
			doOnResponseRecievedDeprecated(response);
			break;
		case PhoneLicensesCodes.REQUEST_CODE_APPINFO:
			doOnResponseRecievedAppInfo(response);
			break;
		default:
			Log.d(TAG, "Got a HTTP resposne but the requestCode ("+requestCode+") was not handled");
			break;
		}
	}



	/**
	 * Parse the XML response for Application information
	 * 
	 * @param response
	 */
	private void doOnResponseRecievedAppInfo(HttpResponse response) {
		//Common code required by all HTTP responses
		if(response==null) {
			Toast.makeText(this, R.string.com_phonelicenses_communication_error , Toast.LENGTH_LONG).show();
			return;
		}
		
		HttpEntity entity = response.getEntity();
		BufferedInputStream bis;
		
		try {
			if(entity != null) {
				InputStream in = entity.getContent();
				bis = new BufferedInputStream(in);
				Utils.logInpuStream(bis);
			}
			else {
				stateError(getString(R.string.com_phonelicenses_empty_response_error));
				return;
			}
		} catch (IllegalStateException e) {
			Log.e(TAG, "IllegalStateException", e);
			return;
		} catch (IOException e) {
			Log.e(TAG, "IOException", e);
			return;
		} finally {
			//hide the progress bar
			progressBarDownloadProgress.setVisibility(View.GONE);
		}
		
		
		XmlResponse<Void> xmlResponse = XmlParser.parseXmlApplication(bis);

		if(xmlResponse.isError()) {
			//notify the user
			showMessageDialog(xmlResponse.getMessage());
			Log.e(TAG, xmlResponse.toString() );	
		} else { //ALL WAS OK
			Log.d(TAG, xmlResponse.getMessage());
			doActivityStateBasedOnLicenseType();
		}
	}






	private void doActivityStateBasedOnLicenseType() {
		switch (AndroidClientLicenseImpl.getInstance().getLicenseType()) {
		case ANDROID_MARKET_FREE:
			stateAndroidMarketFree();
			break;
		case DISABLE_LICENSE:
			stateLicenseDisabled();
			break;
		case ANDROID_MARKET_PAID:
		case PHONE_PAYMENTS_ENABLED:
			stateApplicationInfoDownloaded();
			break;	
		case PHONE_PAYMENTS_DISABLED:	
		default:
			statePaymentsDisabled();
			break;
		}
	}









	/**
	 * Parse the XML response for a Deprecated Application request
	 * 
	 * @param response
	 */
	private void doOnResponseRecievedDeprecated(HttpResponse response) {
		if(response==null) {
			showMessageDialog(R.string.com_phonelicenses_communication_error);
			return;
		}

		HttpEntity entity = response.getEntity();			

		try {
			if(entity!=null) {
				
				InputStream in = entity.getContent();
				BufferedInputStream bis = new BufferedInputStream(in);
				Utils.logInpuStream(bis);

			    StringBuilder sb = new StringBuilder();

			    int c;
			    while ( (c = bis.read()) != -1 ) {
			      sb.append((char)c);
			    }
			    
			    bis.close();
			    
			    //A result of the plain string 'OK' means that application is still available for payments
			    if(sb.toString().equals("OK")) {
			    	this.downloadApplicationInformation();
			    } else {
			    	showMessageDialog(R.string.com_phonelicenses_deprecated);
			    	stateDeprecated();
			    }

				
			} else {
				Log.e(TAG, "An empty response was received from the server");
				stateError(getString(R.string.com_phonelicenses_empty_response_error));
			}

		} catch (IllegalStateException e) {
			showMessageDialog("IllegalStateException");
			Log.e(TAG, "IllegalStateException", e);
		} catch (IOException e) {
			showMessageDialog("IOException");
			Log.e(TAG, "IOException", e);
		}
	}




	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
				
		//Check that we have an XML response before allowing emails
		if( ApplicationDataCache.getInstance().getSupportEmail() == null ) {
			menu.findItem(R.id.menu_ask_question).setVisible(false);
		} 		
		else {
			menu.findItem(R.id.menu_ask_question).setVisible(true);			
		}
		
		//Display the login menu item
		if(PreferencesHelper.isAccountVerified(this)) {
			menu.findItem(R.id.menu_login).setVisible(false);
			menu.findItem(R.id.menu_delete_license).setVisible(true);
		} else {
			menu.findItem(R.id.menu_login).setVisible(true);
			menu.findItem(R.id.menu_delete_license).setVisible(false);
		}
		
		return true;
	}







	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		//inflate the menu
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.com_phonelicenses_menu_main, menu);

		
		return true;
	}






	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);

		switch(item.getItemId()) {
			case(R.id.menu_refresh):
				AndroidClientLicenseImpl.getInstance().reload(this);
				determineViewState();
				return true;
			case(R.id.menu_force_license_download):
				AndroidClientLicenseImpl.getInstance().downloadAndInstallLicense(this);
				return true;
			case(R.id.menu_login):
				Intent intent = new Intent(
						this, 
						com.droidprofessor.android.library.phonelicenses.ActivityLogin.class
						);
				startActivityForResult(intent, PhoneLicensesCodes.REQUEST_CODE_LOGIN);
				return true;
			case(R.id.menu_delete_license):
				AndroidClientLicenseImpl.getInstance().deleteLicense(this);
				PreferencesHelper.setPaymentUnverified(this);
				PreferencesHelper.setTransactionNo(this, "");
				AndroidClientLicenseImpl.getInstance().deleteAccountDetails(this);
				AndroidClientLicenseImpl.getInstance().reload(this);
				determineViewState();
				return true;
			case R.id.menu_ask_question:
				askQuestion();			
				return true;
		}

		return false;
	}
	
	
	
//	/**
//	 * Adds a new payment option to the state
//	 * 
//	 * @param imageResrouce
//	 * @param price
//	 * @param currency
//	 * @param descriptionResource
//	 */
//	private void addPaymentDisplay(int imageResrouce, String price, String currency, final int descriptionResource) {
//		LayoutInflater li = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
//		LinearLayout ll = (LinearLayout)li.inflate(R.layout.com_phonelicenses_payment_button_row,null);
//		ImageView imageView = (ImageView)ll.findViewById(R.id.image);
//		ImageButton helpView = (ImageButton)ll.findViewById(R.id.help);
//		TextView priceView = (TextView)ll.findViewById(R.id.price);
//		
//		imageView.setImageResource(imageResrouce);
//		priceView.setText(price+" "+currency);
//		
//		helpView.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				Utils.showDialogMessage(ActivityMain.this, getString(descriptionResource));
//			}
//		});
//		
//		this.linearLayoutPaymentControls.addView(ll);
//	}
	
	
	
	
	/**
	 * The application information has been downloaded and 
	 * is available in the PaymentProvider class
	 * 
	 */
	private void stateApplicationInfoDownloaded() {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.VISIBLE);
		
		//DESCRIPTION
		this.textViewDescription.setText( 
				Html.fromHtml(
						ApplicationDataCache.getInstance().getDescription()
						) 
					);
		
		//APPLICATION NAME
		this.textViewApplicationName.setText(
						ApplicationDataCache.getInstance().getApplicationName()
						);
		
		populateSpinner();
	}


	private ApplicationDataCache.PaymentMethod selectedPaymentMethod = null;
	
	private void populateSpinner() {

		List<ApplicationDataCache.PaymentMethod> paymentMethods = ApplicationDataCache.getInstance().getEnabledPaymentMethods();

		/*
		 * Test for existance of Android Market
		 */
		boolean androidMarketExists = false;
	    Intent intent = new Intent();
	    intent.setAction(Intent.ACTION_VIEW);
	    intent.setData(Uri.parse("market://search?q=foo"));
	    PackageManager packageManager = getPackageManager();
	    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, 0);

	    if(list.size() > 0)
	    	androidMarketExists=true;
	    
//	    if(Environment.DEBUG) androidMarketExists = true; //Only if we are in debugging mode


		//Android Market only allows their payment system
		if( AndroidClientLicenseImpl.getInstance().getLicenseType() == LicenseType.ANDROID_MARKET_PAID ) {
			ApplicationDataCache.PaymentMethod pm= ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED);
			
			if(!androidMarketExists) {
				Log.e(TAG, "Android Market is not available on the phone");
				Toast.makeText(this, "Your phone does have have the Android Market Installed", Toast.LENGTH_LONG);
				finish();
				return;
			}
			
			
			if(pm == null) {
				Log.e(TAG, "No Android Market payment method was available");
				Toast.makeText(this, "No Android Market Payment method is available, please contact the Developer", Toast.LENGTH_LONG);
				finish();
				return;
			}
			
			if( !pm.isEnabled() ) {
				Log.e(TAG, "The Android Market payment is disabled");
				Toast.makeText(this, "Android Market Payments have been disabled on the server, please contact the Developer", Toast.LENGTH_LONG);
				finish();
				return;
			}
			
			paymentMethods = new ArrayList<PaymentMethod>(1);
			paymentMethods.add(pm);
		}
		
		
	    //Add or remove Android Market Payment
		if(!androidMarketExists) {
			//Remove Android Market if it exists
			ApplicationDataCache.PaymentMethod pm= ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED);
			paymentMethods.remove(pm);
			
			Log.i(TAG, "Android Market has been removed as it is not available on the phone");
		}
		
		
		//The Spinner Adapter
		PaymentMethodsAdapter adapter = new PaymentMethodsAdapter(
	    		this, 
	    		R.layout.com_phonelicenses_payment_row,
	    		R.id.price,
	    		paymentMethods
	    	);
		
	    adapter.setDropDownViewResource(R.layout.com_phonelicenses_dropdown_payment_row);
	    spinnerPaymentMethod.setAdapter(adapter);
	    
	    spinnerPaymentMethod.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapter, View v,
					int position, long id) {
				
				//update the payment method
				selectedPaymentMethod = (ApplicationDataCache.PaymentMethod)adapter.getItemAtPosition(position);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				
			}
		});
	    
	    //Select the first item
	    this.spinnerPaymentMethod.setSelection(0);
	}
	
	
	
	
	class PaymentMethodsAdapter extends ArrayAdapter<ApplicationDataCache.PaymentMethod> {
		List<ApplicationDataCache.PaymentMethod> items;
		
		public PaymentMethodsAdapter(Context context, int resource,
				int textViewResourceId, List<PaymentMethod> objects) {
			super(context, resource, textViewResourceId, objects);
			this.items = objects;
		}

		@Override
		public View getDropDownView(int position, View convertView,
				ViewGroup parent) {
           
			View v = convertView;
			
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.com_phonelicenses_dropdown_payment_row, null);
            }
            
            ApplicationDataCache.PaymentMethod curItem = items.get(position);
            
            //set the price
            TextView price = (TextView)v.findViewById(R.id.price);
            price.setText( curItem.getPrice()+" "+curItem.getCurrency() );
            
            //set the description
            TextView description = (TextView)v.findViewById(R.id.description);
            description.setText(curItem.getDescription());
            
            //set the Image
            ImageView image = (ImageView)v.findViewById(R.id.image);
            image.setImageResource(curItem.getImageResource());
			
			return v;
		}

		@Override
		public ApplicationDataCache.PaymentMethod getItem(int position) {
			return super.getItem(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View v = convertView;
			
            if (v == null) {
                LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.com_phonelicenses_payment_row, null);
            }
            
            ApplicationDataCache.PaymentMethod curItem = items.get(position);
            
            //set the text
            TextView price = (TextView)v.findViewById(R.id.price);
            ImageView image = (ImageView)v.findViewById(R.id.image);
            
            price.setText(curItem.getPrice()+" "+curItem.getCurrency());
            image.setImageResource(curItem.getImageResource());
			
			return v;
		}
		
	}
	
	


	/**
	 * A license in already installed
	 */
	private void stateLicenseInstalled() {
		AndroidClientLicenseImpl.getInstance().reload(this);
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_licensed);
		this.textViewDescription.setText( AndroidClientLicenseImpl.getInstance().getLicenseDetails(this) );	
	}

	
	
	/**
	 * No license in installed
	 */	
	private void stateNoLicense() {
		this.progressBarDownloadProgress.setVisibility(View.VISIBLE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_loading);
		this.textViewDescription.setText( "" );
	}
	
	
	
	/**
	 * Payment is pending approval
	 */
	private void statePaymentPending() {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText("TXN No: "+PreferencesHelper.getTransactionNo(this));
		this.textViewDescription.setText( R.string.com_phonelicenses_payment_pending );	
	}
	
	
	/**
	 * An error occurred
	 * 
	 * @param message
	 */
	private void stateError(String message) {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_press_menu_for_refresh);
		this.textViewDescription.setText( message );	
	}
	
	
	/**
	 * There is no internet connection
	 */
	private void stateNoInternet() {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_press_menu_for_refresh);
		this.textViewDescription.setText( R.string.com_phonelicenses_no_internet );	
	}
	
	
	/**
	 * The license is disabled
	 */
	private void stateLicenseDisabled() {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_full_version);
		this.textViewDescription.setText( R.string.com_phonelicenses_full_version_message );	
	}
	
	
	/**
	 * The application is deprecated
	 */
	private void stateDeprecated() {
		this.progressBarDownloadProgress.setVisibility(View.GONE);
		this.linearLayoutPaymentControls.setVisibility(View.GONE);
		this.textViewApplicationName.setText(R.string.com_phonelicenses_software_upgrade_needed);
		this.textViewDescription.setText( R.string.com_phonelicenses_deprecated );	
	}
	
	
	/**
	 * A special state for the Android Market
	 */
	private void stateAndroidMarketFree() {
		boolean androidMarketEnabled;
		try {
			androidMarketEnabled = (ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED)).isEnabled();
		} catch (Exception e1) {
			//This may happen if the server had stripped out the android market before delivering the xml message, as is the case currently
			Toast.makeText(this, "Sorry, Android Market payments have been disabled by the Developer", Toast.LENGTH_LONG).show();
			androidMarketEnabled = false;
		}
		
		if( !androidMarketEnabled ) {
			//if there is no Android Market, we will default to payment restricted
			statePaymentsDisabled();
			return;
		}

		stateApplicationInfoDownloaded();
		linearLayoutPaymentControls.setVisibility(View.GONE);
		
		String preferredPhoneUrl = ApplicationDataCache.getInstance().getPhoneProductsUrl();
		String url = null;
		
		if(preferredPhoneUrl.length() > 0) {
			url = preferredPhoneUrl;
		} else {
			try {
				url = (new URL(AndroidClientLicenseImpl.getInstance().getScheme(), 
						AndroidClientLicenseImpl.getInstance().getHost(), 
						AndroidClientLicenseImpl.getInstance().getPort(), 
						AndroidClientLicenseImpl.getInstance().getPath())).toString();
			} catch (MalformedURLException e) {
				url = "Not Available";
				e.printStackTrace();
			}
		}
		
		String text = String.format(
				getString(AndroidClientLicenseImpl.getInstance().getLicenseType().getBodyMessage()), 
				url
				);
		
		//create the button if necessary
		createAndroidMarketButton();
	
		this.textViewDescription.setText( Html.fromHtml(text) );	

	}	
		
	
	
	/**
	 * Payment has been restricted
	 */
	private void statePaymentsDisabled() {
		stateApplicationInfoDownloaded();
		linearLayoutPaymentControls.setVisibility(View.GONE);


		String preferredPhoneUrl = ApplicationDataCache.getInstance().getPhoneProductsUrl();
		String url = null;
		
		if(preferredPhoneUrl.length() > 0) {
			url = preferredPhoneUrl;
		} else {
			try {
				url = (new URL(AndroidClientLicenseImpl.getInstance().getScheme(), 
						AndroidClientLicenseImpl.getInstance().getHost(), 
						AndroidClientLicenseImpl.getInstance().getPort(), 
						AndroidClientLicenseImpl.getInstance().getPath())).toString();
			} catch (MalformedURLException e) {
				url = "Not Available";
				e.printStackTrace();
			}
		}
		
		String content = String.format(
				getString(AndroidClientLicenseImpl.getInstance().getLicenseType().getBodyMessage()),
				url
				);

		this.textViewDescription.setText( Html.fromHtml(content) );
	}





	private Button buttonAndroidMarketRedirect;
	private void createAndroidMarketButton() {
		if(buttonAndroidMarketRedirect == null) {
			//Create the button
			buttonAndroidMarketRedirect = new Button(this);
			buttonAndroidMarketRedirect.setText(R.string.com_phonelicenses_get_it);
			buttonAndroidMarketRedirect.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try {
						Intent marketIntent = new Intent(
						Intent.ACTION_VIEW,
						Uri.parse("market://details?id="+
								ApplicationDataCache.getInstance().getPaymentMethodByReferenceName(
										ApplicationDataCache.PaymentMethod.REFNAME_ANDROIDMARKET_INTEGRATED).getExtra("upgradePackage")
								)
						);
						startActivity(marketIntent);
					} catch (Exception e) {
						Toast.makeText(ActivityMain.this, R.string.com_phonelicneses_no_android_market, Toast.LENGTH_LONG).show();
					}
				}
			});
			
			linearLayoutContentHolder.addView(buttonAndroidMarketRedirect,0);

		}
	}
	
}
